package com.smart.service.impl;

import com.smart.pojo.RolePermission;
import com.smart.mapper.RolePermissionMapper;
import com.smart.pojo.User;
import com.smart.req.RolePermissionReq;
import com.smart.service.IRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyj
 * @since 2023-04-19
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IUserService userService;

    @Override
    @Transactional
    public boolean authorizationByRoleId(RolePermissionReq rolePermissionReq) {
        //删除属于该角色的用户的缓存权限
        List<User> userList = userService.lambdaQuery().eq(User::getRoleId, rolePermissionReq.getRoleId()).list();
        List<Long> collect = userList.stream().map(e -> e.getId()).collect(Collectors.toList());
        if (collect != null && !collect.isEmpty()) {
            redisTemplate.opsForHash().delete("permission", collect.toArray());
        }

        //先删除原有
        boolean remove = this.lambdaUpdate().eq(RolePermission::getRoleId, rolePermissionReq.getRoleId()).remove();

        //再插入最新数据
        ArrayList<RolePermission> rolePermissions = new ArrayList<>();
        for (Long aLong : rolePermissionReq.getPermissionList()) {
            rolePermissions.add(new RolePermission(rolePermissionReq.getRoleId(), aLong));
        }
        boolean rs = this.saveBatch(rolePermissions);
        return remove | rs;
    }
}
